package data

import (
	"context"
	"glmall-product/internal/biz"

	"github.com/go-kratos/kratos/v2/log"
)

type categoryRepo struct {
	data *Data
	log  *log.Helper
}

// NewGreeterRepo .
func NewCategoryRepo(data *Data, logger log.Logger) biz.CategoryRepo {
	return &categoryRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

func (r *categoryRepo) Create(ctx context.Context, category *biz.PmsCategory) error {
	return r.data.db.WithContext(ctx).Create(category).Error
}

func (r *categoryRepo) Get(ctx context.Context, id int64) (*biz.PmsCategory, error) {
	var category biz.PmsCategory
	err := r.data.db.WithContext(ctx).Where("cat_id = ?", id).First(&category).Error
	return &category, err
}

func (r *categoryRepo) Update(ctx context.Context, category *biz.PmsCategory) error {
	return r.data.db.WithContext(ctx).Save(category).Error
}

func (r *categoryRepo) Delete(ctx context.Context, id int64) error {
	return r.data.db.WithContext(ctx).Delete(&biz.PmsCategory{}, id).Error
}

func (r *categoryRepo) List(ctx context.Context) ([]*biz.PmsCategory, error) {
	var categories []*biz.PmsCategory
	err := r.data.db.WithContext(ctx).Find(&categories).Error
	return categories, err
}

func (r *categoryRepo) Count(ctx context.Context, parentId *int64, showStatus *bool) (int64, error) {
	var count int64
	db := r.data.db.WithContext(ctx).Model(&biz.PmsCategory{})

	if parentId != nil {
		db = db.Where("parent_cid = ?", *parentId)
	}
	if showStatus != nil {
		db = db.Where("show_status = ?", *showStatus)
	}

	err := db.Count(&count).Error
	return count, err
}

func (r *categoryRepo) BatchCreate(ctx context.Context, categories []*biz.PmsCategory) error {
	return r.data.db.WithContext(ctx).CreateInBatches(categories, 100).Error
}

// ListWithTree implements biz.CategoryRepo.
func (r *categoryRepo) ListWithTree(ctx context.Context) ([]*biz.PmsCategory, error) {
	return r.List(ctx)
}
